#include <iostream>
#include <string>
#include "typeinfo.h"
#include "stdlib.h"
#include "list.h"

using namespace std;

/*
 * 删除递增单链表内，满足A到B开区间内数值的节点
 *
 * @param listOne  SingleList* 类型的指针
 * @param a  int 开区间最小值
 * @param b int  开区间最大值
 *
 */
void cutFromAtoB(SingleList *listOne, int a, int b){
    if(a >b ||listOne->getHead() == NULL){
        return ;
    }
    LNode * pHead, *pTemp,*pCurrent;
    pTemp =pHead = pCurrent = listOne->getHead();
    while(pCurrent != NULL){
        if(pCurrent->link != NULL){
            if(pCurrent->data >a && pCurrent->data < b){
                //如果是第一个节点，则移动头指针
                if(pHead ==pCurrent){
                    //接后续节点,为删除节点最准备
                    pTemp = pHead = pHead->link;
                    //删除满足条件的节点
                    delete(pCurrent);
                    pCurrent = pTemp;
                }else{
                    //删除满足条件的节点
                    pTemp->link = pCurrent->link; //接后续节点
                    delete(pCurrent);
                    pCurrent = pTemp->link; //移动cur指针
                }

            }else if(pCurrent->data >b){
                break;
            }else{
                pTemp =  pCurrent; // 移动临时指针 
                pCurrent = pCurrent->link;
            }
        }else{
            pCurrent = NULL;
        }
    }

    //将单链表的头指针指向新链表的第一个节点
    listOne->setHead(pHead);

    return; 
}

int main(){

    cout << "请输入0~10个随机数字，每输入一个按Enter键，最后输入任意字母表示结束.\n";
    SingleList ListOne;
    int n=0;
    int i=0;

    while(cin >>n){
        if(typeid(n) != typeid(int)){
            break;
        }
        if(ListOne.getLast() !=NULL && ListOne.getLast()->data >n){
           cout <<"请输入非递减数列(大于):"<<ListOne.getLast()->data <<"\n";
           continue;
        }
        LNode *node = new LNode(n);
        ListOne.insert(node, ListOne.getLen());
        i++;
    }
    //输出输入结果
    cout << "链表一:";
    ListOne.output();
    cout <<"链表长度：" <<ListOne.getLen()<<"\n"<<endl;

    int from;
    int to;
    cin.clear();
    cout <<"按回车键继续\n";
    getchar();
    cout << "请输入下界值：";
    while(cin >> from ){
        if(typeid(from) != typeid(int)){
            cout << "请输入数字:\n";
        }else{
            break;
        }
    }
    cout << "请输入上界值：";
    while(cin >> to ){
        if(typeid(to) != typeid(int)){
            cout << "请输入数字:\n";
        }else{
            break;
        }
    }

    //调用截取函数
     cutFromAtoB(&ListOne, from, to);

     cout <<"截取结果："<<endl;
     //输出结果
     ListOne.output();
}
